//
//  CustomCalloutView.m
//  CarLifes
//
//  Created by yu on 2017/6/27.
//  Copyright © 2017年 jpas. All rights reserved.
//

#define kArrorHeight        10

#define kPortraitMargin     5
#define kPortraitWidth      70
#define kPortraitHeight     50

#define kTitleWidth         120
#define kTitleHeight        20

#import "CustomCalloutView.h"
#import "CalloutInfoCell.h"
#import "TraceModel.h"

#define kCalloutCellIdentifier @"CalloutInfoCellId"

@interface CustomCalloutView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, copy  ) NSString *address;
@property (nonatomic, strong) TraceModel *traceModel;

@end

@implementation CustomCalloutView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = [UIColor clearColor];
        
        [self.tableView registerNib:NIB_NAMED(@"CalloutInfoCell") forCellReuseIdentifier:kCalloutCellIdentifier];
        [self addSubview:self.tableView];
        
        self.tableView.sd_layout
        .topSpaceToView(self, 6)
        .leftEqualToView(self)
        .rightEqualToView(self)
        .heightIs(180);
        
        self.buttonView = [[ButtonsView alloc] init];
        [self addSubview:self.buttonView];
        
        self.buttonView.sd_layout
        .topSpaceToView(self.tableView, 6)
        .leftSpaceToView(self, 0)
        .rightSpaceToView(self, 0);
        
        [self setupAutoHeightWithBottomView:self.buttonView bottomMargin:20];
    }
    return self;
}

- (void)setModel:(EquipmentModel *)model
{
    _model = model;
    // 用来标记点击的是哪个标注点
    [self.buttonView setModel:model];
}

- (void)setTModel:(TraceModel *)tModel
{
    _tModel = tModel;
    [self.tableView reloadData];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.scrollEnabled = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.titles.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CalloutInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:kCalloutCellIdentifier];
    cell.titleLabel.text = _titles[indexPath.row];
    NSString *cnStatus = [_model.cnStatus stringByReplacingOccurrencesOfString:@" " withString:@""];
//    PPLog(@"cnstatus = %@",_model.cnStatus);
    if (!cnStatus.length) {
        cnStatus = @"未知";
    }
    
    switch (indexPath.row)
    {
        case 0:
            cell.contentLabel.text = _model.ownerName;
            break;
        case 1:
            cell.contentLabel.text = _model.eqNo;
            break;
        case 2:
            cell.contentLabel.text = cnStatus;
            break;
        case 3:
            cell.contentLabel.text = self.tModel.positionTime;
            break;
        case 4:
            cell.contentLabel.text = self.tModel.postType;
            break;
        case 5:
            cell.contentLabel.text = self.tModel.address;
            break;
        default:
            break;
    }
    return cell;
}

#pragma mark - UIPasteboard -
- (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    return action == @selector(copy:) ? YES : NO;
}

- (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
{
    if (action == @selector(copy:)) {
        
        CalloutInfoCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
        
        NSString *copyStr = [NSString stringWithFormat:@"%@%@",cell.titleLabel.text,cell.contentLabel.text];
        [pasteBoard setString:copyStr];
//        PPLog(@"copyContent++>%@",pasteBoard.string);
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (NSArray *)titles {
    if (!_titles) {
        _titles = @[@"车主:",@"设备号:",@"状态:",@"定位时间:",@"定位方式:",@"当前位置:"];
    }
    return _titles;
}

#define mark - draw -
- (void)drawRect:(CGRect)rect {
    
    [self drawInContext:UIGraphicsGetCurrentContext()];
    
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowOpacity = 0.5;
    self.layer.shadowOffset = CGSizeMake(2.0f, 2.0f);
}

- (void)drawInContext:(CGContextRef)context {
    
    UIColor *bgColor;
    if (@available(iOS 13.0, *)) {
        bgColor = UIColor.secondarySystemGroupedBackgroundColor;
    } else {
        bgColor = UIColor.whiteColor;
    }
    CGContextSetLineWidth(context, 2.0);
    CGContextSetFillColorWithColor(context, bgColor.CGColor);
    [self getDrawPath:context];
    CGContextFillPath(context);
}

- (void)getDrawPath:(CGContextRef)context {
    
    CGRect rrect = self.bounds;
    CGFloat radius = 6.0;
    CGFloat minx = CGRectGetMinX(rrect),
    midx = CGRectGetMidX(rrect),
    maxx = CGRectGetMaxX(rrect);
    CGFloat miny = CGRectGetMinY(rrect),
    maxy = CGRectGetMaxY(rrect)-kArrorHeight;
    
    CGContextMoveToPoint(context, midx+kArrorHeight, maxy);
    CGContextAddLineToPoint(context,midx, maxy+kArrorHeight);
    CGContextAddLineToPoint(context,midx-kArrorHeight, maxy);
    
    CGContextAddArcToPoint(context, minx, maxy, minx, miny, radius);
    CGContextAddArcToPoint(context, minx, minx, maxx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, maxx, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextClosePath(context);
}

@end


@implementation ButtonsView

- (instancetype)init
{
    if (self = [super init])
    {
        self.backgroundColor = UIColor.clearColor;
        self.userInteractionEnabled = YES;
        
        // 指令下发、电子栅栏一期去掉
        NSArray *picImageNamesArr = @[@"path",@"restart_location",@"follow",@"user_info",@"navigator",@"device_alarm",@"command"];
        NSArray *nameArr = @[@"轨迹回放",@"重新定位",@"实时跟踪",@"用户信息",@"一键追车",@"设备报警"];
        
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        self.temp = [NSMutableArray array];
        for (int i = 0; i < nameArr.count; i++) {
            UIButton *button = [[UIButton alloc] init];
            self.button = button;
            [self addSubview:button];
            
            [button setTitle:nameArr[i] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:picImageNamesArr[i]] forState:UIControlStateNormal];
            if (@available(iOS 13.0, *)) {
                UIColor *btnColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
                    if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                        return kTextBlackColor;
                    } else {
                        return kDarkTextColor;
                    }
                }];
                [button setTitleColor:btnColor forState:UIControlStateNormal];
            } else {
                [button setTitleColor:kTextBlackColor forState:UIControlStateNormal];
            }
            button.titleLabel.font = SYSTEM_FONT(10);
            button.titleLabel.textAlignment = NSTextAlignmentCenter;
            button.imageView.contentMode = UIViewContentModeScaleAspectFit;
            button.tag = i + 100;
            
            [button addTarget:self action:@selector(functionAction:) forControlEvents:UIControlEventTouchUpInside];
            
            // 设置button的图片的约束
            button.imageView.sd_layout
            .widthRatioToView(button, 1)
            .topSpaceToView(button, 5)
            .centerXEqualToView(button)
            .heightEqualToWidth();
            
            // 设置button的label的约束
            button.titleLabel.sd_layout
            .topSpaceToView(button.imageView, 5)
            .bottomSpaceToView(button, 1)
            .leftSpaceToView(button, -10)
            .rightSpaceToView(button, -10);
            
            // 设置高度约束
            button.sd_layout.autoHeightRatio(1.5);
            [temp addObject:button];
        }
        
        for (UIButton *btn in temp) {
            if (btn.tag == 105 || btn.tag == 106 || btn.tag == 107) {
                btn.sd_layout.autoHeightRatio(0);
                btn.hidden = YES;
            }
            
            if (btn.tag == 104) {
                [btn setTitle:@"更多" forState:UIControlStateNormal];
                [btn setImage:IMAGE_NAMED(@"more") forState:UIControlStateNormal];
            }
        }
        
        self.temp = temp;
        [self setupAutoMarginFlowItems:[temp copy] withPerRowItemsCount:5 itemWidth:35 verticalMargin:5 verticalEdgeInset:0 horizontalEdgeInset:15];
    }
    return self;
}

#pragma mark - function action -
- (void)functionAction:(UIButton *)btns
{
    NSInteger btnTag = btns.tag;
    
    if (btnTag == 104)
    {
        [btns setTitle:@"一键追车" forState:UIControlStateNormal];
        [btns setImage:IMAGE_NAMED(@"navigator") forState:UIControlStateNormal];
        btns.tag = 888;
        
        for (UIButton *btn in self.temp) {
            if (btn.tag == 105 || btn.tag == 106 || btn.tag == 107)
            {
                btn.hidden = NO;
                [self updateLayout];
                btn.sd_layout.autoHeightRatio(1.5);
            }
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kSendBtnTitleNotification object:self.model userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@(btnTag),@"tag",nil]];
}

@end

